<?php
namespace App\Actions;

use App\Models\AdminUser;
use App\Models\Department;
use App\Models\DepartmentFile;
use App\Models\departmentFushu;
use App\Models\DepartmentStaff;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class DepartmentFileUploadAction extends BaseAction
{
    public $department;
    public $admin_user;

    public function __construct(Department $department = null, AdminUser $adminUser = null)
    {
        $this->department = $department;
        $this->admin_user = $adminUser;
    }

    public function getFileOriginName($file)
    {
        # 获取原始文件名称
        $origin_name = pathinfo($file, PATHINFO_FILENAME);
        $_position = mb_strrpos($origin_name, '_'); # 这里处理是因为文件在上传过程中会自动加一个时间戳字符串，防止文件名重复
        $origin_name= mb_substr($origin_name, 0, $_position);
        return $origin_name;
    }

    public function upload($file, $office_file_type = 'pdf')
    {
        $department = $this->department;
        DB::beginTransaction();
        $department_file = DepartmentFile::query()->where('department_id', $department->id)->where('dwdm', $department->dwdm)->first();
        
        # 获取原始文件名称
        $extension = pathinfo($file, PATHINFO_EXTENSION);
        $origin_name= $this->getFileOriginName($file);

        # 获取文件应该按照要求的命名规则
        $should_origin_name = $department->getFileShouldName();

        if ($should_origin_name != $origin_name) {
            $this->error('文件名称错误，文件名称应该为“'.$should_origin_name.'”' );
        }

        # 新文件地址 班子考核表/pdf(ppt)/单位名称/文件名称.pdf
        $prefix = $department->getDirPrefix();
        $subprefix = $office_file_type == 'pdf' ? 'pdf' : 'ppt';
        $newpath = $prefix. "/{$subprefix}/" . $department->dwmc . "/" . $should_origin_name . "."  . $extension;

        # 如果有重名的需要先删除之前的文件
        if (file_exists(file_local_path($newpath))) {
            @unlink(file_local_path($newpath));
        }
        # 复制上传的文件到新文件地址
        Storage::disk('public')->copy($file, $newpath);

        if (!$department_file) {
            $department_file = new DepartmentFile([
                'department_id' => $department->id,
                'dwdm' => $department->dwdm,
                'extension' => $extension
            ]);
            $department_file->save();
        }
        # 上传的是PDF文件
        if ($office_file_type == 'pdf') {
            $department_file_origin_file = $department_file->pdf_filepath;
            $department_file->pdf_filepath = $newpath;
        } else {
            # 上传的是PPT
            $department_file_origin_file = $department_file->ppt_filepath;
            $department_file->ppt_filepath = $newpath;
        }
        $department_file->save();
        $this->resetDepartmentStatus();
        DB::commit();

        # 如果文件不相同，则删除，其实也没必要，后面考虑删除这里
        if ($department_file_origin_file && $department_file_origin_file != $newpath && file_exists(file_local_path($department_file_origin_file))) {
            @unlink(file_local_path($department_file_origin_file));
        }

        # 删除原始上传的文件
        if (file_exists(file_local_path($file))) {
            @unlink(file_local_path($file));
        }
        return $department_file;
    }


    /**
     * 上传领导人员文件
     */
    public function uploadStaff($files, Department $department)
    {
        $errors = [];
        foreach($files as $file)
        {
            # 获取原始文件名称
            $extension = pathinfo($file, PATHINFO_EXTENSION);
            $origin_name= $this->getFileOriginName($file);
            $name = str_replace('考核表', '', $origin_name);

            # 判断是否存在这个用户
            $department_staff = DepartmentStaff::query()->where('name', $name)->where('dwdm', $department->dwdm)->first();
            if (!$department_staff) {
                array_push($errors, $name . '人员不存在');
            } else {
                # 新文件地址 班子考核表/pdf(ppt)/单位名称/文件名称.pdf
                $prefix = $department->getDirPrefix();
                $subprefix = 'pdf';
                $filename = $department_staff->name . '考核表';
                $newpath = $prefix. "/{$subprefix}/" . $department->dwmc . "/" . $filename . "."  . $extension;

                # 如果有重名的需要先删除之前的文件
                if (file_exists(file_local_path($newpath))) {
                    @unlink(file_local_path($newpath));
                }
                # 复制上传的文件到新文件地址
                Storage::disk('public')->copy($file, $newpath);

                $department_staff->update(['filepath' => $newpath]);
            }
        }
        $this->resetDepartmentStatus();
        if ($errors) {
            $this->error(implode("<br/>", $errors));
        }
    }

    /**
     * 上传附属单位的文件
     */
    public function uploadFuShu($files, Department $department)
    {
        $errors = [];
        foreach($files as $file)
        {
            # 获取原始文件名称
            $extension = pathinfo($file, PATHINFO_EXTENSION);
            $origin_name= $this->getFileOriginName($file);
            $fs_dwmc = str_replace('班子考核表', '', $origin_name);

            # 判断是否存在这个用户
            $department_fushu = departmentFushu::query()->where('fs_dwmc', $fs_dwmc)->where('dwdm', $department->dwdm)->first();
            if (!$department_fushu) {
                array_push($errors, $fs_dwmc . '单位不存在，请确定文件名称必须与要求的一致');
            } else {
                $prefix = $department->getDirPrefix();
                $subprefix = 'pdf';
                $filename = $department_fushu->fs_dwmc . '班子考核表';
                $newpath = $prefix. "/{$subprefix}/" . $department->dwmc . "/" . $filename . "."  . $extension;

                # 如果有重名的需要先删除之前的文件
                if (file_exists(file_local_path($newpath))) {
                    @unlink(file_local_path($newpath));
                }
                # 复制上传的文件到新文件地址
                Storage::disk('public')->copy($file, $newpath);

                $department_fushu->update(['filepath' => $newpath]);
            }
        }
        $this->resetDepartmentStatus();
        if ($errors) {
            $this->error(implode("<br/>", $errors));
        }
    }

    public function resetDepartmentStatus()
    {
        $this->department->update(['status' => Department::STATUS_NORMAL, 'fail_reason' => null]);
    }

    
}